/*
 * Licensed under the MIT License
 * 
 * Copyright (c) 2011 Kay Kreuning
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 * 
 * http://code.google.com/p/hyves-as3-sdk/
 */
package nl.hyves.api.utils
{
	import flash.net.SharedObject;
	import nl.hyves.api.core.Consumer;
	import nl.hyves.api.core.OAuthToken;


	public class TokenStorage
	{
		private var consumer:Consumer;
		private var id:String;

		public function TokenStorage(consumer:Consumer)
		{
			this.consumer = consumer;

			id = AuthUtil.hash(consumer.key + '.' + consumer.secret);
		}

		public function has():Boolean
		{
			var data:Object = SharedObject.getLocal(id).data;

			if (data && data.expiredate)
			{
				var expiredate:Number = data.expiredate * 1000;
				var currentdate:Number = new Date().getTime() - 1000;
				// Subtract one second just to be sure (network delay, etc.)

				return expiredate > currentdate;
			}

			return false;
		}

		public function get():OAuthToken
		{
			if (has())
			{
				var data:Object = SharedObject.getLocal(id).data;

				var token:OAuthToken = new OAuthToken();
				token.oauth_token = data.oauth_token;
				token.oauth_token_secret = data.oauth_token_secret;
				token.userid = data.userid;
				token.methods = data.methods;
				token.expiredate = data.expiredate;

				return token;
			}

			return null;
		}

		public function set(token:OAuthToken):Boolean
		{
			var so:SharedObject = SharedObject.getLocal(id);
			var data:Object = so.data;
			
			data.oauth_token = token.oauth_token;
			data.oauth_token_secret = token.oauth_token_secret;
			data.userid = token.userid;
			data.methods = token.methods;
			data.expiredate = token.expiredate;

			so.flush();

			return has();
		}
		
		public function clear():void
		{
			SharedObject.getLocal(id).clear();
		}
	}
}
